﻿
@{
    ViewData["Title"] = "Index";
    Layout = "_OridinaryPage";
}

@section Header{
    <link rel="stylesheet" href="~/js/plugins/bootstrap-table/bootstrap-table.css" />
    <link rel="stylesheet" href="~/js/plugins/zTree/css/metroStyle/metroStyle.css" />
    <link rel="stylesheet" href="~/css/zTree.css" />
}

<section>
    <!--<h2>
        <small></small>
    </h2>-->
    <ol class="breadcrumb breadcrumb-pd clear-mgb bg-transparent">
        <li><a href="#"><i class="fa fa-dashboard"></i> 系统管理</a></li>
        <li class="active">角色管理</li>
    </ol>
</section>
<!-- Main content -->
<section class="content-mini clear-pdt clear-pdb">
    <div class="row">
        <div class="col-xs-12">
            <div class="box  clear-mgb clearBoxTopBorder clearShadow">
                <!--<div class="box-header">
                    <h3 class="box-title"></h3>
                </div>-->
                <!-- /.box-header -->
                <div class="box-body clear-pd">
                    <div id="toolbar" class="btn-group">
                        @if (BaseHelper.HasPermission(SysRoleBtn.Add))
                        {
                            <button id="btnAdd" type="button" class="btn btn-default" data-toggle="modal" data-target="#addEditModal">
                                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加
                            </button>
                        }
                        @if (BaseHelper.HasPermission(SysRoleBtn.Edit))
                        {
                            <button id="btnEdit" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
                            </button>
                        }
                        @if (BaseHelper.HasPermission(SysRoleBtn.Delete))
                        {
                            <button id="btnDelete" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                            </button>
                        }
                    </div>
                    <table id="dataInfos" class="table table-bordered table-hover"></table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<!-- /.content -->
<!-- addEditModal---start -->
<div id="addEditModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="addEditModal">
    <div class="modal-dialog modal-md" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">添加角色</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="addEditForm">
                    <div class="form-group">
                        <label for="addEditRoleCode" class="col-sm-2 control-label">角色编码</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditRoleCode" name="RoleCode" placeholder="角色编码" maxlength="50">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditRoleName" class="col-sm-2 control-label">角色名称</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditRoleName" name="RoleName" placeholder="角色名称" maxlength="50">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditRoleType" class="col-sm-2 control-label">角色类型</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditRoleType" name="RoleType" placeholder="角色类型" maxlength="50">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditRemarks" class="col-sm-2 control-label">备注</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditRemarks" name="Remarks" placeholder="备注" value="无" maxlength="200">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="btnAddEditSubmit" class="btn btn-primary">提交</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("#btnAddEditSubmit").click(function () {
        var roleCode = $("#addEditRoleCode").val();
        var roleName = $("#addEditRoleName").val();
        var roleType = $("#addEditRoleType").val();
        var remarks = $("#addEditRemarks").val();
        if (IsNullOrEmpty(roleCode)) {
            alert("请输入角色编码！");
            $("#addEditRoleCode").focus();
            return;
        }
        if (IsNullOrEmpty(roleName)) {
            alert("请输入角色名称！");
            $("#addEditRoleName").focus();
            return;
        }
        if (IsNullOrEmpty(roleType)) {
            alert("请输入角色类型！");
            $("#addEditRoleType").focus();
            return;
        }
        if (IsNullOrEmpty(remarks)) {
            alert("请输入备注！");
            $("#addEditRemarks").focus();
            return;
        }
        IndexBtnDisabled();
        $.ajax({
            type: "post",
            url: $("#addEditRoleCode").attr("readonly") == "readonly" ? "/Sys/Sys_Role/Edit" : "/Sys/Sys_Role/Add",
            data: $("#addEditForm").serialize(),
            dataType: "json",
            success: function (data) {
                if (data.Success) {
                    alert(data.Message);
                    $("#addEditModal").modal('hide');
                    $("button[name='refresh']").click();
                } else {
                    alert(data.Message);
                }
                IndexBtnEnabled();
            },
            error: function (err) { }
        });
    });
</script>
<!-- addEditModal---end -->
<!-- setMenuModal---start -->
<div id="setMenuModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="setMenuModal">
    <div class="modal-dialog modal-md" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">设置资源</h4>
            </div>
            <div class="modal-body" style="height: 500px;overflow-y: scroll;">
                <input type="hidden" id="setMenuRoleCode" />
                <ul id="treeDemo" class="ztree"></ul>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="btnSetMenuSubmit" class="btn btn-primary">提交</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("#btnSetMenuSubmit").click(function () {
        var addMenuIds = "";
        var deleteMenuIds = "";
        var roleCode = $("#setMenuRoleCode").val();
        $("#setMenuRoleCode").val();
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        var changedNodes = treeObj.getChangeCheckedNodes();
        if (changedNodes.length < 1) {
            alert("资源未发生变化！");
            return;
        }
        IndexBtnDisabled();
        for (var i = 0; i < changedNodes.length; i++) {
            if (changedNodes[i].checked) {
                addMenuIds += changedNodes[i].menuId;
                addMenuIds += ",";
            } else {
                deleteMenuIds += changedNodes[i].menuId;
                deleteMenuIds += ",";
            }
        }
        if (addMenuIds.endsWith(",")) {
            addMenuIds = addMenuIds.substr(0, addMenuIds.length - 1);
        }
        if (deleteMenuIds.endsWith(",")) {
            deleteMenuIds = deleteMenuIds.substr(0, deleteMenuIds.length - 1);
        }
        console.info("addMenuIds=" + addMenuIds);
        console.info("deleteMenuIds=" + deleteMenuIds);
        console.info("roleCode=" + roleCode);
        $.ajax({
            type: "post",
            url: "/Sys/Sys_Role_Menu/UpdateRelation",
            data: "addMenuIds=" + addMenuIds + "&deleteMenuIds=" + deleteMenuIds + "&roleCode=" + roleCode,
            dataType: "json",
            success: function (data) {
                if (data.Success) {
                    alert(data.Message);
                    $("#setMenuModal").modal('hide');
                    $("button[name='refresh']").click();
                } else {
                    alert(data.Message);
                }
                IndexBtnEnabled();
            },
            error: function (err) { }
        });
    });
</script>
<!-- setMenuModal---end -->

@section Scripts{
    <script src="~/js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="~/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
    <script src="~/js/plugins/zTree/js/jquery.ztree.all.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();
        });

        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#dataInfos').bootstrapTable({
                    url: '/Sys/Sys_Role/GetPageList',   //请求后台的URL（*）
                    method: 'get',                      //请求方式（*）
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    sortable: true,                     //是否启用排序
                    sortName: "CreateDate",             //排序字段
                    sortOrder: "desc",                  //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                      //初始化加载第一页，默认第一页
                    pageSize: 15,                       //每页的记录行数（*）
                    pageList: [10, 15, 20, 30, 50],     //可供选择的每页的行数（*）
                    search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                    searchOnEnterKey: true,
                    strictSearch: true,
                    showColumns: true,                  //是否显示所有的列
                    showRefresh: true,                  //是否显示刷新按钮
                    minimumCountColumns: 2,             //最少允许的列数
                    clickToSelect: true,                //是否启用点击选中行
                    //height: 811,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "RoleCode",                 //每一行的唯一标识，一般为主键列
                    showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
                    cardView: false,                    //是否显示详细视图
                    detailView: false,                  //是否显示父子表
                    columns: [{
                        checkbox: true
                    }, {
                        field: 'RoleName',
                        title: '角色名称'
                    }, {
                        field: 'RoleCode',
                        title: '角色编码'
                    }, {
                        field: 'Creator',
                        title: '创建人'
                    }, {
                        field: 'CreateDate',
                        title: '创建时间',
                        sortable: true,
                        formatter: function (value, row, index) {
                            return getFormatDate(value);
                        }
                    }, {
                        field: 'Remarks',
                        title: '备注'
                    }, {
                        field: 'RoleCode',
                        title: '操作',
                        formatter: 'operateFormatter'
                    }],
                    onLoadSuccess: function (res) {  //加载成功时执行
                        //console.info("加载成功");
                    },
                    onLoadError: function () {  //加载失败时执行
                        //console.info("加载数据失败");
                    }
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {   //这里键的名字和控制器的变量名必须一致，如有变动此处和控制器要一起改
                    rowsPerPage: params.limit, //每页数据行数
                    offsetRows: params.offset, //已偏移行数
                    sortName: params.sort,
                    sortOrder: params.order,
                    search: $("div.search input").val()
                    //search: params.search
                };
                return temp;
            };
            return oTableInit;
        };

        //格式化操作列的内容
        function operateFormatter(value, row, index) {
            var array = [];
            @if (BaseHelper.HasPermission(SysRoleBtn.Edit))
            {
                @:array.push("<a onclick='showEditModal(" + JSON.stringify(row) + ")' class='operateLink'><i class='fa fa-pencil-square-o' ></i>&nbsp;编辑</a>");
            }
            @if (BaseHelper.HasPermission(SysRoleBtn.SetMenu))
            {
                @:array.push('<a onclick="showSetMenuModal(\'' + value + '\')" class="operateLink"><i class="fa fa-cog" ></i>&nbsp;设置资源</a>');
            }
            return array.join('');
        }

        $("#btnAdd").click(function () {
            $(".clear").val('');
            $("#addEditModal .modal-title").text("添加角色");
            $("#addEditRoleCode").removeAttr("readonly");
            $("#addEditRemarks").val('无');
        });

        $("#btnEdit").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择要修改的条目！");
                return;
            }
            if (selections.length > 1) {
                alert("只能选择一条要修改的条目！");
                return;
            }
            showEditModal(selections[0]);
        });

        function showEditModal(row) {
            if (IsNullOrEmpty(row.RoleCode)) {
                alert("数据异常，请联系管理员！");
                return;
            }
            $("#addEditModal .modal-title").text("编辑角色");
            $("#addEditRoleCode").attr("readonly", "readonly");
            $("#addEditRoleCode").val(row.RoleCode);
            $("#addEditRoleName").val(row.RoleName);
            $("#addEditRoleType").val(row.RoleType);
            $("#addEditRemarks").val(row.Remarks);
            $("#addEditModal").modal('show');
        }

        $("#btnDelete").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择要删除的条目！");
                return;
            }
            if (!confirm("请确认删除！")) return;
            var ids = "";
            for (var i = 0; i < selections.length; i++) {
                ids += selections[i].RoleCode + ",";
            }
            if (ids.endsWith(",")) {
                ids = ids.substr(0, ids.length - 1);
            }
            $.ajax({
                type: "post",
                url: "/Sys/Sys_Role/Delete",
                data: "ids=" + ids,
                dataType: "json",
                success: function (data) {
                    if (data.Success) {
                        alert(data.Message);
                        $("button[name='refresh']").click();
                    } else {
                        alert(data.Message);
                    }
                },
                error: function (err) { }
            });
        });

        function showSetMenuModal(roleCode) {
            var zTreeObj;
            //zTree的参数配置，深入使用请参考 API 文档（setting 配置详解）
            var setting = {
                check: {
                    autoCheckTrigger: false,
                    chkboxType: { "Y": "ps", "N": "ps" },
                    chkStyle: "checkbox",
                    enable: true
                }
            };
            //zTree的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
            var zNodes = [
                {
                    name: "test1", open: true, children: [
                        { name: "test1_1" }, { name: "test1_2" }]
                },
                {
                    name: "test2", open: true, children: [
                        { name: "test2_1" }, { name: "test2_2" }]
                }
            ];
            $.ajax({
                url: "/Sys/Sys_Menu/GetMenuPermissionList",
                data: "roleCode=" + roleCode,
                dataType: "json",
                success: function (data) {
                    $("#setMenuRoleCode").val(roleCode);
                    zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, data);
                    $("#setMenuModal").modal('show');
                },
                error: function (err) { }
            });
        }
    </script>
}
